﻿/**
 * Created by zhangcb on 2016/12/5.
 */
define(['ldfw/core', './loading','jquery-weui'],
    function (LDFW,loading) {

        var _compare, _fileTypeSettings, _fileTypes

        _compare = function (input, str, exact) {
            return input !== undefined && (exact ? input === str : str.test(input));
        }
        _fileTypeSettings = {
            image: function (vName) {
                return false || _compare(vName, /\.(gif|png|jpe?g)$/i);
            },
            html: function (vName) {
                return false || _compare(vName, /\.(htm|html)$/i);
            },
            text: function (vName) {
                return _compare(vName, /\.(xml|javascript)$/i) ||
                    _compare(vName, /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);
            },
            video: function (vName) {
                return false ||
                    _compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i);
            },
            audio: function (vName) {
                return false || (_compare(vName, /(ogg|mp3|mp?g|wav)$/i) ||
                    _compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
            },
            flash: function (vName) {
                return false || _compare(vName, /\.(swf)$/i);
            },
            pdf: function (vName) {
                return false || _compare(vName, /\.(pdf)$/i);
            },
            object: function () {
                return true;
            },
            other: function () {
                return true;
            }
        }

        _fileTypes = ["image", "html", "text", "video", "audio", "flash", "pdf", "object"]

        $.ajaxSettings = $.extend($.ajaxSettings,{
            beforeSend: function () {
                loading.show()
            },
            dataType: 'json',
            error: function (jqXHR, textStatus, errorMsg) {
                $.alert('Error[' + jqXHR.status + ']:' + errorMsg)
            },
            success: function (resp, textStatus, jqXHR) {
                if (resp.resultCode && resp.resultCode === '1208') {
                    window.sessionStorage.clear()
                    LDFW.navigate('login')
                    return
                } else if (resp.resultCode) {
                    let cause = ''
                    try {
                        cause = JSON.parse(resp.cause || {})
                    } catch (e) {
                        cause = resp.cause
                    }
                    if (cause==null || (typeof cause == 'object' && cause.errorLevel == 1 )) {
                        $.alert(resp.resultMsg && resp.resultMsg.match(/[^\x00-\xff]/g).join(''))
                        return
                    }
                }
            },
            complete:function(){
                loading.hide()
            }
        },true)


        function getUrl(functionCode,suffix){
            let origin = window.location.origin
            let url = origin + '/' + functionCode + '.json';
            if (suffix) {
                url = url.replace('.json', suffix)
            }
            return url;
        }
        function xhr(type, url, data, options) {
            if (url.indexOf('.do') > -1) {
                let functionCode = url.substr(0, url.indexOf('.do'))
                let suffix = '.do'
                url = getUrl(functionCode, suffix)
            } else {
                url = getUrl(url)
            }
            data.row_count = data.row_count || -1
            options = $.extend(true, {
                url:url,
                timeout: 5000,
                data: data,
                type: type
            }, options)
            return $.ajax(options)
        }
        //jquery的ajax不支持文件流
        function getFileAsBolb(url, data,option) {
            return new Promise(function (resolve, reject) {
                let xhr = new XMLHttpRequest();
                xhr.timeout = 30000;
                xhr.open(option.type||'POST', url, true);
                xhr.responseType = 'blob';
                xhr.withCredentials = true;
                xhr.onload = function (e) {
                    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
                        let disposition = xhr.getResponseHeader('Content-Disposition'),
                            filename = ''
                        if(disposition && disposition.indexOf('attachment')!==-1){
                            let fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                            let matches = fileNameRegex.exec(disposition);
                            if (matches != null && matches[1]){
                                filename = decodeURI(matches[1].replace(/['"]/g, ''))
                            }
                        }
                        if(parseFileType(filename)==='audio'){
                            resolve(new Blob([xhr.response],{type:'audio/mpeg'}))
                        }else{
                            resolve(xhr.response)
                        }
                    } else {
                        reject(new Error(xhr.statusText));
                    }
                }
                xhr.onerror = function (e) {
                    reject(e)
                }
                xhr.send(data)
            })
        }


         function parseFileType(fileName) {
            var isValid, cat, i, types = _fileTypes;
            for (i = 0; i < types.length; i++) {
                cat = types[i];
                isValid = _fileTypeSettings[cat];
                var vType = isValid(fileName) ? cat : '';
                if (vType) {
                    return vType;
                }
            }
            return 'other';
        }

        return {
            get: function (url, data) {
                var promise = xhr('GET', url, data || {})
                promise.success = promise.done
                promise.error = promise.fail
                return promise
            },
            post: function (url, data) {
                var promise = xhr('POST', url, data || {});
                promise.success = promise.done
                promise.error = promise.fail
                return promise
            },

            upload:function(url, data){
                var promise = xhr('POST', url, data, {
                    cache: false,
                    processData: false, // Don't process the files
                    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                })
                promise.success = promise.done
                promise.error = promise.fail
                return promise
            },

            preview(url, data,option){
                let formData = new FormData();
                for (let key in data) {
                    formData.append(key, data[key]);
                }
                url = option && option.notProcessUrl ? url : getUrl(url, '.do')
                let promise = getFileAsBolb(url, formData, option||{})
                promise.success = function (fn) {
                    promise.then(fn)
                    return promise
                }
                promise.fail = function (fn) {
                    promise.then(null, fn)
                    return promise
                }
                return promise
            },
            sync:function(type,url,data){
                var promise = xhr(type, url, data || {},{
                    async:false
                })
                promise.success = promise.done
                promise.error = promise.fail
                return promise
            }
        }
    })
